import axios from 'axios';
import { message } from 'antd';

const defaultConfig = {
    // 如果请求话费了超过 `timeout` 的时间，请求将被中断
    timeout: 3000
}

const _request = (params = {}, fn = () => {}) => {
    return axios({...defaultConfig, ...params})
    .then(res => {
        const { code, success, data, err } = res.data;
        // 用户没有访问权限，将跳转到首页
        if (code === 401) {
            window.location.href = '/';
            return;
        }

        if (success) {
            fn(false);
            return data;
        }
        throw err;
    }).catch(err => {
        fn(false);
        message.err(String(err || '网络错误'));
    })
}

export default (param) => {
    const type = typeof param;

    if (type === 'function') {
        param(true);
        return obj => _request(obj, param);
    }

    if (type === 'object' && type != null) {
        return _request(param);
    }
}